package tech.yangzhijie.basic.knowledge.mianshi;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test05WriteWriteThread {

    public static void main(String[] args) {
        WriteWriteData writeWriteData = new WriteWriteData();
        CountDownLatch countDownLatch = new CountDownLatch(100000);
        for (long i = 1; i <= 100000; i++) {
            final long num = i;
            new Thread(()->{
                writeWriteData.write(num);
                countDownLatch.countDown();
            }).start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最后写入值为: " + writeWriteData.getNum());
    }

}


class WriteWriteData{
    private long num;

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

    public long getNum() {
        return num;
    }

    /**
     * 不加锁
     * 4999500334
     * 4999910613
     * 4999345874
     *
     * 加锁
     * 5000050000
     * 5000050000
     * 5000050000
     */
    public void write(long num){
        writeLock.lock();
        try {
            System.out.println("线程 " + Thread.currentThread().getName()+ " 开始写入");
            this.num += num;
            System.out.println("线程 " + Thread.currentThread().getName()+ " 写入完成");
        } finally {
            writeLock.unlock();
        }
    }
}
